<template>
  <div class="t-profit-chart">
    <div class="chart-header">
      <div class="header-left">
        <h2>{{ stockName || '股票' }}做T收益分析</h2>
      </div>
      <div class="header-right">
        <div class="navigation-controls">
          <el-button-group>
            <el-button size="small" @click="navigatePrevious">
              <i class="el-icon-arrow-left"></i>
              {{ chartType === 'year' ? '上一年' : '上个月' }}
            </el-button>
            <span class="current-period">{{ getCurrentPeriodText() }}</span>
            <el-button size="small" @click="navigateNext">
              {{ chartType === 'year' ? '下一年' : '下个月' }}
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </el-button-group>
        </div>
        <el-radio-group v-model="chartType" size="small" @change="handleTypeChange">
          <el-radio-button label="year">年度视图</el-radio-button>
          <el-radio-button label="month">月度视图</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon profit">
          <i class="el-icon-caret-top"></i>
        </div>
        <div class="stat-content">
          <div class="stat-label">总收益</div>
          <div class="stat-value" :class="{ 'profit': totalProfit >= 0, 'loss': totalProfit < 0 }">
            {{ formatCurrency(totalProfit) }}
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon average">
          <i class="el-icon-data-analysis"></i>
        </div>
        <div class="stat-content">
          <div class="stat-label">{{ chartType === 'year' ? '月均收益' : '日均收益' }}</div>
          <div class="stat-value" :class="{ 'profit': averageProfit >= 0, 'loss': averageProfit < 0 }">
            {{ formatCurrency(averageProfit) }}
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon max">
          <i class="el-icon-top"></i>
        </div>
        <div class="stat-content">
          <div class="stat-label">最高收益</div>
          <div class="stat-value profit">{{ formatCurrency(maxProfit) }}</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon min">
          <i class="el-icon-bottom"></i>
        </div>
        <div class="stat-content">
          <div class="stat-label">最低收益</div>
          <div class="stat-value loss">{{ formatCurrency(minProfit) }}</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon count">
          <i class="el-icon-date"></i>
        </div>
        <div class="stat-content">
          <div class="stat-label">交易天数</div>
          <div class="stat-value">{{ this.processedData.length > 0
          ? (this.processedData.filter(item => {
              if(!item.isFilled){
                return item
              }
          })).length
          : 0 }}</div>
        </div>
      </div>
    </div>

    <div class="chart-container">
      <div class="chart-title">
        <h3>{{ chartType === 'year' ? '年度收益走势' : '月度收益走势' }}</h3>
        <span class="chart-subtitle">{{ chartType === 'year' ? '12个月收益分布' : '当月每日收益' }}</span>
      </div>

      <div class="chart-wrapper">
        <div ref="echartsContainer"
             class="echarts-container"
             :style="{
                display: loading || processedData.length === 0 ? 'none' : 'block' 
            }">
        </div>

        <div v-if="loading" class="loading-chart">
          <i class="el-icon-loading"></i>
          <p>加载中...</p>
        </div>

        <div v-else-if="processedData.length === 0" class="empty-chart">
          <i class="el-icon-data-line"></i>
          <p>暂无数据</p>
        </div>
      </div>
    </div>

    <div class="chart-footer">
      <div class="summary-info">
        <span>数据更新时间: {{ currentDate }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import {listStockTTransaction} from '@/api/stockTTransaction'
import * as echarts from 'echarts'

export default {
  name: 'TProfitChart',
  props: {
    stockCode: {
      type: String,
      required: true
    },
    type: {
      type: String,
      default: 'year',
      validator: value => ['year', 'month'].includes(value)
    },
    stockName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chartType: this.type,
      currentDate: new Date().toLocaleDateString('zh-CN'),
      loading: false,
      chartData: [],
      echartsInstance: null,
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1
    }
  },
  computed: {
    processedData() {
      if (!this.chartData || this.chartData.length === 0) {
        console.log('原始数据为空或无效');
        return [];
      }

      // 过滤有效数据
      const validData = this.chartData.filter(item =>
          item &&
          item.tprofit !== null &&
          item.tprofit !== undefined &&
          !isNaN(parseFloat(item.tprofit))
      );

      if (validData.length === 0 && this.chartType !== 'month') {
        console.log('没有有效的收益数据');
        return [];
      }

      // 处理数据
      let processed = validData.map(item => {
        const profit = parseFloat(item.tprofit || 0);
        let label, date;

        if (this.chartType === 'year') {
          label = `${item.month || '未知'}月`;
          date = `${item.month || '未知'}月`;
          return {
            ...item,
            profit: profit,
            label: label,
            date: date,
            originalDate: new Date(item.transactionDate || item.date || `${new Date().getFullYear()}-${item.month}-01`)
          };
        } else {
          // 月度视图：使用具体日期
          const transDate = item.transactionDate || item.date;
          if (transDate) {
            const dateObj = new Date(transDate);
            label = `${dateObj.getDate()}日`;
            date = transDate;
            return {
              ...item,
              profit: profit,
              label: label,
              date: date,
              originalDate: dateObj
            };
          }
          return null;
        }
      }).filter(Boolean);

      if (this.chartType === 'month') {
        // 获取当月第一天和最后一天
        const firstDay = new Date(this.currentYear, this.currentMonth - 1, 1);
        const lastDay = new Date(this.currentYear, this.currentMonth, 0);

        // 创建完整的日期数组
        const completeData = [];
        const existingDataMap = new Map();

        // 将现有数据按日期索引
        processed.forEach(item => {
          const dateKey = item.originalDate.getDate();
          if (existingDataMap.get(dateKey) != null) {
            let tempItem = existingDataMap.get(dateKey);
            tempItem.tprofit += item.tprofit;
            existingDataMap.set(dateKey, tempItem);
          } else {
            existingDataMap.set(dateKey, item);
          }
        });

        // 生成当月完整日期数据
        for (let day = 1; day <= lastDay.getDate(); day++) {
          const currentDate = new Date(this.currentYear, this.currentMonth - 1, day);
          const dateKey = day;

          if (existingDataMap.has(dateKey)) {
            // 使用现有数据
            completeData.push(existingDataMap.get(dateKey));
          } else {
            // 补全缺失日期，tprofit为0
            completeData.push({
              label: `${day}日`,
              date: currentDate.toISOString().split('T')[0],
              profit: 0,
              tprofit: 0,
              originalDate: currentDate,
              isFilled: true // 标记为补全的数据
            });
          }
        }

        processed = completeData;
      } else {
        // 年度视图：按月份排序
        processed.sort((a, b) => a.originalDate - b.originalDate);
      }

      return processed;
    },
    totalProfit() {
      console.log("chartData:" + this.chartData)
      return (this.chartData || []).reduce((sum, item) => sum + item.tprofit, 0);
    },
    averageProfit() {
      return this.processedData.filter(item => {
              if(!item.isFilled){
                return item
              }}).length > 0
          ? this.totalProfit / (this.processedData.filter(item => {
              if(!item.isFilled){
                return item
              }
          })).length
          : 0;
    },
    maxProfit() {
      return this.processedData.length > 0
          ? Math.max(...this.processedData.map(item => item.tprofit))
          : 0;
    },
    minProfit() {
      return this.processedData.filter(item => {
              if(!item.isFilled){
                return item
              }}).length > 0
          ? Math.min(...this.processedData.filter(item => {
              if(!item.isFilled){
                return item
              }}).map(item => {
                return item.tprofit
          }))
          : 0;
    }
  },
  watch: {
    type(newVal) {
      this.chartType = newVal;
    },
    stockCode: {
      handler(newCode) {
        if (newCode) {
          this.fetchData();
        }
      },
      immediate: true
    },
    chartType() {
      this.fetchData();
    },
    processedData: {
      handler(newData) {
        console.log('数据变化，重新初始化图表');
        if (newData.length > 0) {
          this.initChart();
        } else if (this.echartsInstance) {
          // 清空图表
          this.echartsInstance.clear();
        }
      },
      deep: true
    },
    originalData() {
      return this.processedData.filter(item => !item.isFilled);
    }
  },
  mounted() {
    this.fetchData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    if (this.echartsInstance) {
      this.echartsInstance.dispose();
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    navigatePrevious() {
      if (this.chartType === 'year') {
        this.currentYear--;
      } else {
        this.currentMonth--;
        if (this.currentMonth < 1) {
          this.currentMonth = 12;
          this.currentYear--;
        }
      }
      this.fetchData();
    },
    navigateNext() {
      if (this.chartType === 'year') {
        this.currentYear++;
      } else {
        this.currentMonth++;
        if (this.currentMonth > 12) {
          this.currentMonth = 1;
          this.currentYear++;
        }
      }
      this.fetchData();
    },
    getCurrentPeriodText() {
      if (this.chartType === 'year') {
        return `${this.currentYear}年`;
      } else {
        return `${this.currentYear}年${this.currentMonth}月`;
      }
    },
    async fetchData() {
      if (!this.stockCode) {
        console.log('股票代码为空，不获取数据');
        return;
      }

      this.loading = true;
      console.log(`开始获取 ${this.stockCode} 的${this.chartType === 'year' ? '年度' : '月度'}数据`);

      try {
        const params = {
          stockCode: this.stockCode
        };

        // 根据图表类型设置时间范围
        if (this.chartType === 'year') {

          params.startDate = `${this.currentYear}-01-01`;
          params.endDate = `${this.currentYear}-12-31`;
        } else {
          params.startDate = `${this.currentYear}-${this.currentMonth}-01`;
          const lastDay = new Date(this.currentYear, this.currentMonth, 0).getDate();
          params.endDate = `${this.currentYear}-${this.currentMonth}-${String(lastDay).padStart(2, '0')}`;
        }

        console.log('API请求参数:', params);

        const response = await listStockTTransaction(params);
        console.log('API响应:', response);

        if (response.code === 200 && response.data) {
          console.log('获取到数据条数:', response.data.length);
          console.log('数据示例:', response.data.slice(0, 3));

          // response.data 如果获取的是年度的数据,需要按照月份进行汇总
          // this.chartData =  汇总后的数据
          console.log('chartType：:', this.chartType);
          if (this.chartType === 'year') {
            const newData = this.summarizeDataByMonth(response.data);
            this.chartData = newData;
          } else {
            this.chartData = response.data.filter(item =>
                item.tprofit !== null &&
                item.tprofit !== undefined &&
                !isNaN(parseFloat(item.tprofit))
            );
          }

          console.log('过滤后数据条数:', this.chartData.length);

          if (this.chartData.length === 0) {
            console.log('所有数据都被过滤掉了');
          }
        } else {
          console.log('API返回空数据或错误');
          this.chartData = [];
        }
      } catch (error) {
        console.error('获取做T收益数据失败:', error);
        this.chartData = [];
      } finally {
        this.loading = false;
      }
    },
    summarizeDataByMonth(data) {
      // 初始化12个月的汇总数据
      const monthlyData = [];
      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];

      // 创建每个月的初始数据对象，格式与processedData期望的一致
      for (let i = 0; i < 12; i++) {
        monthlyData.push({
          label: months[i],
          tprofit: 0, // 使用tprofit字段保持与原始数据格式一致
          month: i + 1, // 月份数字1-12
          transactionDate: `${new Date().getFullYear()}-${String(i + 1).padStart(2, '0')}-01`,
          originalDate: new Date(new Date().getFullYear(), i, 1),
          isFilled: true, // 标记为补全数据
          stockCode: this.stockCode,
          stockName: this.stockName
        });
      }

      // 如果输入数据为空，返回12个空月份
      if (!data || data.length === 0) {
        return monthlyData;
      }

      // 按月份汇总数据
      const monthlyProfits = Array(12).fill(0);
      const hasDataMonths = new Set();

      data.forEach(item => {
        if (item.transactionDate && item.tprofit !== undefined) {
          const date = new Date(item.transactionDate);
          const monthIndex = date.getMonth(); // 0-11
          if (monthIndex >= 0 && monthIndex < 12) {
            monthlyProfits[monthIndex] += Number(item.tprofit) || 0;
            hasDataMonths.add(monthIndex);
          }
        }
      });

      // 更新汇总后的数据
      monthlyData.forEach((monthData, index) => {
        if (hasDataMonths.has(index)) {
          monthData.tprofit = monthlyProfits[index];
          monthData.isFilled = false; // 有实际数据的月份
        }
      });


      return monthlyData;
    },
    initChart() {
      this.$nextTick(() => {
        if (!this.$refs.echartsContainer || this.processedData.length === 0) {
          return;
        }

        if (!this.echartsInstance) {
          this.echartsInstance = echarts.init(this.$refs.echartsContainer);
        }

        // 准备图表数据
        const xAxisData = this.processedData.map(item => item.label);
        const seriesData = this.processedData.map(item => ({
          value: item.tprofit,
          itemStyle: {
            // 补全的数据使用不同颜色，负值使用更醒目的红色
            color: item.isFilled ? '#ff4757' : (item.tprofit >= 0 ? '#ff4757' : '#5470c6')
          }
        }));

        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              const data = params[0];
              const item = this.processedData[params[0].dataIndex];
              const prefix = item.isFilled ? '[补全] ' : '';
              return `${prefix}${data.name}<br/>收益: ${this.formatCurrency(data.value)}`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
              rotate: this.chartType === 'month' ? 45 : 0,
              // 补全数据的标签使用灰色
              color: (value, index) => {
                return this.processedData[index]?.isFilled ? '#999' : '#333';
              }
            }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: (value) => this.formatCurrency(value)
            }
          },
          series: [{
            data: seriesData,
            type: 'line',
            smooth: true,
            lineStyle: {
              color: this.processedData.some(item => item.tprofit < 0 && !item.isFilled) ? '#ff4757' : '#5470c6',
              width: 2
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {offset: 0, color: 'rgba(84, 112, 198, 0.3)'},
                {offset: 1, color: 'rgba(84, 112, 198, 0.1)'}
              ])
            },
            // 补全数据使用虚线连接
            connectNulls: false,
            // 添加数据标签显示
            label: {
              show: true,
              position: 'top',
              formatter: (params) => {
                const item = this.processedData[params.dataIndex];
                // 补全的数据不显示标签
                if (item.isFilled) return '';
                return this.formatCurrency(params.value, true);
              },
              fontSize: 12,
              fontWeight: 'bold',
              color: (params) => {
                const item = this.processedData[params.dataIndex];
                if (item.isFilled) return '#e0e0e0';
                return params.value >= 0 ? '#00c851' : '#ff4757';
              }
            },
            // 添加数据点标记
            symbol: 'circle',
            symbolSize: 6,
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              },
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
            }
          }]
        };

        this.echartsInstance.setOption(option);
      });
    },

    handleResize() {
      if (this.echartsInstance) {
        this.echartsInstance.resize();
      }
    },

    handleTypeChange(type) {
      this.chartType = type;
      this.$emit('type-change', type);
    },

    formatCurrency(value, short = false) {
      if (short && Math.abs(value) >= 1000) {
        return (value >= 0 ? '+' : '') + (value / 1000).toFixed(1) + 'k';
      }
      return (value >= 0 ? '+' : '') + value.toFixed(2);
    }
  }
}
</script>

<style scoped>
.t-profit-chart {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}

.header-left h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.stock-code {
  font-size: 14px;
  color: #7f8c8d;
  margin-left: 10px;
}

.header-right {
  display: flex;
  align-items: center;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
}

.stat-icon.profit {
  background: linear-gradient(135deg, #00c851, #00ff00);
  color: white;
}

.stat-icon.average {
  background: linear-gradient(135deg, #36d1dc, #5b86e5);
  color: white;
}

.stat-icon.max {
  background: linear-gradient(135deg, #11998e, #38ef7d);
  color: white;
}

.stat-icon.min {
  background: linear-gradient(135deg, #fc466b, #3f5efb);
  color: white;
}

.stat-icon.count {
  background: linear-gradient(135deg, #f093fb, #f5576c);
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: 700;
}

.stat-value.profit {
  color: #00c851;
}

.stat-value.loss {
  color: #ff4444;
}

.chart-container {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.chart-title {
  text-align: center;
  margin-bottom: 30px;
}

.chart-title h3 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 20px;
}

.chart-subtitle {
  color: #7f8c8d;
  font-size: 14px;
}

.chart-wrapper {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.echarts-container {
  width: 100%;
  height: 400px;
}

.loading-chart, .empty-chart {
  text-align: center;
  color: #7f8c8d;
}

.loading-chart i, .empty-chart i {
  font-size: 48px;
  margin-bottom: 10px;
}

.chart-footer {
  margin-top: 20px;
  text-align: center;
}

.summary-info {
  font-size: 12px;
  color: #7f8c8d;
}

@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    gap: 15px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .echarts-container {
    height: 300px;
  }
}

.navigation-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.current-period {
  font-weight: bold;
  color: #409EFF;
  padding: 0 10px;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 10px;
}
</style>